#ifndef O_LARGEFILE
#define O_LARGEFILE 0100000
#endif
#define _GNU_SOURCE
#define _LARGEFILE_SOURCE  
#define _LARGEFILE64_SOURCE  
#define _FILE_OFFSET_BITS 64
#include <jni.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <stdint.h>
#include <limits.h>
#include <sys/file.h>
#include "tr_edu_ozyegin_ccrg_raid_rawdisk_DiskWriter.h"

JNIEXPORT jboolean JNICALL Java_tr_edu_ozyegin_ccrg_raid_rawdisk_DiskWriter_storeFile
  (JNIEnv * env, jobject jobj, jstring name, jbyteArray buffer, jlong blockID, jlong blockSize){
    int fd;
  //unsigned char *buffer;
  int i, j,readed=0;
	//buffer = (char *)malloc((int)((uint64_t)blockSize));
uint64_t BlockSize = (uint64_t)blockSize ;
uint64_t BlockID  = (uint64_t)blockID;
jboolean iscopy;
      const jchar *mfile = (*env)->GetStringUTFChars(env, name, &iscopy);
  fd = open64(mfile, O_WRONLY | O_LARGEFILE);
  if (fd < 0){
    return (jboolean)0;
  } //end-if
  readed = 0;
  if(BlockID !=0){
  	int i;
  	uint64_t seeked = 0;
  	//uint64_t toSeek = BlockSize * BlockID;
  	//printf("resultant where to seek: %llu\n",toSeek);
  	//seeked = lseek(fd,(long)blockSize,SEEK_SET);
  	seeked = lseek64(fd,BlockID,SEEK_SET);
  	/*while(seeked != ((long)blockSize * (long)blockID)){
  			uint64_t res;
  			printf("%llu now\n",(res = lseek64(fd,BlockSize,SEEK_CUR)));
  			printf("res %d\n",res);
  			if(res<=0)break;
  			seeked = res;
  		
  		printf("seeked %llu\n",seeked);
  	}*/
  	//printf("seeked %llu\n",seeked);
  }
  //file opened
 //printf("%lu , %lu \n",(long)blockID,(long)blockSize);
  jbyte *bytes = (*env)->GetByteArrayElements(env,buffer,NULL);
  if(!bytes)printf("empty\n");
  char *buf = (char *)bytes; 
  //putchar(buf[0]);
  //putchar(buf[1]);
  //putchar(buf[2]);
  //putchar(buf[3]);
  //putchar(buf[4]);
  readed = 0;
  //while(1){
  	readed = write(fd, buf, (int)(blockSize));
	if(readed <=0) return (jboolean)0;
  	//printf("%d , %lu \n",(int)readed,(long)blockSize);
  	//if(readed == (int)blockSize || readed<=0) break;
  //}
//printf("%d bytes\n",readed);
  (*env)->ReleaseStringChars(env, name, mfile);
  (*env)->ReleaseByteArrayElements(env, buffer,bytes, 0);
//free(buffer);
  close(fd);
    //return (jb);
  return (jboolean)1;
}
